package com.ftg.learn.chapter03;

/**
 * 二分
 *
 * @author lijiaxin
 * @version 1.0
 * @date 2023/5/13 14:52
 */

public class BinarySearch {

    /**
     * 假如说有一组 有序的数
     * start 开始
     * end 末尾
     * target  目标
     *
     * @return true|false
     */
    public static boolean BinarySearch(int start, int end, int target) {

        checkException(start, end);
        return BinarySearchReal(start, end, target);
    }

    //容错处理
        private static void checkException(int start,int end){
        if (start > end) {
            throw new RuntimeException("参数有问题");
        }
    }

    //        计算功能
        private static boolean BinarySearchReal(int start,int end,int target){
        if (start == end) {
            return start == target;
        }
        while (start <= end) {
            int middle = end + start >> 1;
            if (middle == target) {
                return true;
            } else if (middle < target) {
                start = middle + 1;
            } else {
                end = middle - 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(BinarySearch(1, 10, 7));
    }

}
